
import os, time, shutil, datetime

class null_item():
    def __init__(self,price):
        self.price = price
        self.owner = 'None'
        self.type = 'null_item'
    def load_data(self):
        pass
    def sell(self):
        pass
    def save(self):
        pass
            

class item():
    def __init__(self, consignor, item_file=None):
        timestamp = time.localtime()
        self.consignor = consignor
        self.type = 'item'
        self.consignor_split = consignor.consignor_split
        self.timestamp = '%i/%i/%i' % (timestamp.tm_mon,timestamp.tm_mday,timestamp.tm_year)
        self.cons_path = consignor.cons_path
        if item_file == None:
            self.item_number = consignor.next_available_item_number()
            self.owner = consignor.full_name
            self.owner_number = consignor.number
            self.original_price = '0.00'
            self.consign_date = consignor.consign_date
            self.description = 'General Merchandise'
            self.status = 'In Stock'
            self.location = 'Sales Floor'
            self.sold_date = 'Unsold'
            self.sale_price = '0.00'
            self.sale_location = 'Unsold'
            self.item_file = os.path.join(consignor.cons_path,'%s.info' % self.item_number)

        else:
            self.item_file = item_file
            self.load_data()
        
    def load_data(self):
        f = open(self.item_file,'r')
        lines = f.readlines()
        f.close()
      
        self.item_number = lines[0].strip()
        self.owner_number = lines[1].strip()
        self.owner = lines[2].strip()
        self.original_price = lines[3].strip()
        self.consign_date = lines[4].strip()
        self.description = lines[5].strip()
        self.status = lines[6].strip()
        self.location = lines[7].strip()
        self.sold_date = lines[8].strip()
        self.sale_price = lines[9].strip()
        self.sale_location = lines[10].strip()
        
    def set_item_number(self,number):
        self.item_number = number
        self.item_file = os.path.join(consignor.cons_path,'%s.info' % self.item_number)
        
    def sell(self):
        timestamp = time.localtime()
        timestamp = '%i/%i/%i' % (timestamp.tm_mon,timestamp.tm_mday,timestamp.tm_year)        
        consignor_due = float(self.sale_price)*self.consignor_split
        old_owed = float(self.consignor.last_owed_amount) 
        self.consignor.last_owed_amount = '%.2f' % (old_owed + consignor_due)
        self.consignor.last_five_oweds.pop(0)
        self.consignor.last_five_oweds.append([self.consignor.last_owed_amount,''])
      
        self.status = 'Sold %s' % timestamp
        self.location = self.status
        self.sold_date = timestamp
        self.save()
        self.consignor.save()
        new_path = os.path.join(self.cons_path,'sold')
        if not os.path.exists(new_path):
            os.mkdir(new_path)
        fname = self.item_file.split('/')[-1]
        self.delete()
        self.item_file = os.path.join(new_path,fname)
        self.save()
        self.consignor.sold_dict[self.item_number] = self
        
        
    def set_original_price(self,price):
        self.original_price = price
        self.sale_price = price
          
    def save(self):
        lines = [self.item_number,self.owner_number,self.owner,self.original_price,self.consign_date,self.description,self.status,self.location,self.sold_date,self.sale_price,self.sale_location]
        f = open(self.item_file,'w')
        for line in lines:
            f.writelines(str(line)+'\n')
        f.close()
        
    def delete(self):
        if os.path.exists(self.item_file):
            os.remove(self.item_file)
        self.consignor.item_dict.pop(self.item_number)
        

class consignor():
    def __init__(self,parent,cons_file=None):
        self.consignor_split = parent.consignor_split
        self.localtime = time.localtime()
        self.timestamp = '%i/%i/%i' % (self.localtime.tm_mon,self.localtime.tm_mday,self.localtime.tm_year)      
        self.boothPath = parent.boothPath        
        if cons_file == None:
            self.number = parent.next_available_consignor_number()
            self.cons_path = os.path.join(self.boothPath,self.number)
            self.cons_file = os.path.join(self.cons_path,'consignordata')
            self.first_name = ''
            self.last_name = ''
            self.full_name = ''
            self.split_name = ['','']
            self.address = ['','','']
            self.addy1 = self.address[0]
            self.addy2 = self.address[1]
            self.addy3 = self.address[2]
            self.phone_number = ''
            self.email_address = ''
            self.consign_date = self.timestamp
            self.last_five_oweds = [['0',''],['0',''],['0',''],['0',''],['0','']]
            self.last_owed = self.last_five_oweds[-1]
            self.last_owed_amount = self.last_owed[0]
            self.last_owed_comments = self.last_owed[1]
            self.sold_dict = {}
            self.item_dict = {}
        
        else:
            self.cons_path = cons_file[:-13]
            self.cons_file = cons_file
            self.load_data()
            self.sold_dict = {}
            self.item_dict = {}
            self.load_items()
            
    def set_number(self,number):
        self.number = number
        self.cons_path = os.path.join(self.boothPath,self.number)
        self.cons_file = os.path.join(self.cons_path,'consignordata')
            
    
    def load_data(self):
        f = open(self.cons_file,'r')
        lines = f.readlines()
        f.close()
        self.number = lines[0].strip()
        self.full_name = lines[1].strip()
        self.split_name = self.full_name.split()
        self.first_name = self.split_name[0]
        self.last_name = self.split_name[-1]
        self.reversed_name = '%s, %s' % (self.last_name, self.first_name)
        self.addy1 = lines[2].strip()
        self.addy2 = lines[3].strip()
        self.addy3 = lines[4].strip()
        self.phone_number = lines[5].strip()
        self.email_address = lines[6].strip()
        self.consign_date = lines[7].strip()
        self.last_five_oweds = []
        for line in lines[8:]:
            self.last_five_oweds.append(line.strip().split(','))          
        self.last_owed = self.last_five_oweds[-1]
        self.last_owed_amount = self.last_owed[0]
        self.last_owed_comments = self.last_owed[1]
        
    def save(self):
        
        if not os.path.exists(self.cons_path):
            os.mkdir(self.cons_path)
            
        lines = [self.number,self.full_name,self.addy1,self.addy2,self.addy3,self.phone_number,self.email_address,self.consign_date]
        for owed in self.last_five_oweds:
            lines.append('%s,%s' % (owed[0],owed[1]))           
        f = open(self.cons_file,'w')
        for line in lines:
            f.writelines(line+'\n')
        f.close()
        
    def load_items(self):
        
        for fname in os.listdir(self.cons_path):
            if '.info' in fname:
                item_file = os.path.join(self.cons_path,fname)
                it = item(self,item_file)
                item_number = it.item_number
                self.item_dict[item_number] = it
        solddir = os.path.join(self.cons_path,'sold')        
        if os.path.exists(solddir):        
            for fname in os.listdir(solddir):
                if '.info' in fname:
                    item_file = os.path.join(solddir,fname)
                    it = item(self,item_file)
                    date_format = "%m/%d/%Y"
                    datestamp = datetime.datetime.strptime(it.sold_date, date_format)
                    datestamp = datetime.date(datestamp.year,datestamp.month,datestamp.day)
                    today = datetime.date.today()
                    diff = today - datestamp
                    
                    if diff.days < 90:
                        item_number = it.item_number
                        self.sold_dict[item_number] = it
                        
        
    def payout(self,pay_amount,comments):
        pay_amount = float(pay_amount)
        self.last_five_oweds.pop(0)
        self.last_five_oweds.append( ['%.2f' % (float(self.last_owed_amount) - pay_amount), '%s' % comments ] )
        self.last_owed = self.last_five_oweds[-1]
        self.last_owed_amount = self.last_owed[0]
        self.last_owed_comments = self.last_owed[1]
        self.save()
        
    def next_available_item_number(self):
        numbers = self.item_dict.keys()+self.sold_dict.keys()
        for i in range(0,len(numbers)):
            numbers[i] = float(numbers[i])
        if len(numbers) == 0:
            next_number = '1'
        else:
            next_number = max(numbers) + 1
            next_number = '%i' % next_number
        return(next_number)
        
        
class store():
    def __init__(self,parent):
        self.boothPath = parent.boothPath
        self.storeCreditPath = parent.storeCreditPath
        self.consignor_split = parent.consignor_split
        self.load_consignors()
        self.load_store_credit()
        
    def load_consignors(self):
        self.cons_dict = {}
        for root, dirs, files in os.walk(self.boothPath):
            for name in files:
                if name == 'consignordata':
                    cons = consignor(self,os.path.join(root,name))
                    cons_num = cons.number
                    self.cons_dict[cons_num] = cons
                    
    def load_store_credit(self):
        self.store_credit_dict = {}
        self.store_credit_file = os.path.join(self.storeCreditPath,'Accounts.csv')
        if os.path.exists(self.store_credit_file):
            f = open(self.store_credit_file,'r')
            lines = f.readlines()
            f.close()
            for line in lines:
                num,name,amount = line.strip().split(',')
                self.store_credit_dict[num] = [name,amount]
            
    def save_store_credit(self):
        f = open(self.store_credit_file,'w')
        for key in self.store_credit_dict.keys():
            name_amount = self.store_credit_dict[key]
            num, name, amount = key,name_amount[0],name_amount[1]
            f.writelines('%s,%s,%s\n' % (num,name,amount))
        f.close()
         
    
    def get_item(self,consignor_number,item_number,price):
    
        if not consignor_number in self.cons_dict.keys():
            cons = consignor(self)
            cons.set_number(consignor_number)
            cons.save() 
            self.cons_dict[consignor_number] = cons
            print 'Consignor not found, created consignor with given number'
        if not item_number in self.cons_dict[consignor_number].item_dict.keys():
            cons = self.cons_dict[consignor_number]
            it = item(cons)
            it.item_number = item_number
            it.original_price = price
            it.save()
            cons.item_dict[item_number] = it
            print 'Item not found, created item with given number and price'
        else:
            it = self.cons_dict[consignor_number].item_dict[item_number]
            
        return(it)

    def discount_item_by_percent(self,consignor_number,item_number,percent):
        percent = float(percent)
        cons = self.cons_dict[consignor_number]
        it = cons.item_dict[item_number]
        it.sale_price = float(it.original_price)*(1.-percent)
        
        return(it.sale_price)
        
    def set_item_price(self,consignor_number,item_number,new_price):
        cons = self.cons_dict[consignor_number]
        it = cons.item_dict[item_number]
        it.sale_price = new_price
        
        return(it.sale_price)
              
    def next_available_consignor_number(self):
        numbers = self.cons_dict.keys()
        for i in range(0,len(numbers)):
            numbers[i] = float(numbers[i])
        if len(numbers) == 0:
            next_number = '1'
        else:
            next_number = max(numbers) + 1
            next_number = '%i' % next_number
            
        return(next_number)
        
    def add_null_item(self,price):
        it = null_item(price)
        return(it)
        
    def add_new_consignor(self):
        cons = consignor(self)
        self.cons_dict[cons.number] = cons
        return(cons)
            
    def add_new_item(self,cons_number):
        cons = self.cons_dict[cons_number]
        it = item(cons)
        cons.item_dict[it.item_number] = it
        return(it)
        
    def find_consignor_by_name(self,in_name):
 
        names = in_name.split(' ')
        matches = []
        match = 0
        for key in self.cons_dict.keys():
            cons = self.cons_dict[key]
            if in_name.lower() == cons.full_name.lower():
                return(cons)
            first_name = cons.first_name
            last_name = cons.last_name
            for name in names:
                if name.lower() == first_name.lower() or name.lower() == last_name.lower():
                    return(cons)

        
        
            
        
        

            
        
        
        
            
            
        
